// 单一数据源 state，state它是只读，只能通过reducer纯函数来修改，reducer纯函数返回一个新的state

export const createStore = (reducer) => {
  let state = undefined
  const tasks = new Set()

  const getState = () => {
    return Object.freeze(state)
  }

  const dispatch = (action) => {
    if ({}.toString.call(action) != '[object Object]') {
      throw new Error('action必须为对象，且对象中一定要有属性type')
    }
    if (!action.type) {
      throw new Error('对象中一定要有属性type')
    }

    state = reducer(state, action)
    // 通过订阅者更新
    tasks.forEach((cb) => cb())

    return action
  }

  const subscribe = (cb) => {
    // 订阅
    tasks.add(cb)
    // 取消订阅
    return () => {
      tasks.delete(cb)
    }
  }

  // 初始化数据，给state添加用户指定的state数据
  dispatch({ type: '@@init@@' })

  return {
    getState,
    dispatch,
    subscribe
  }
}
